package com.project.hqshorttaxi.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.project.hqshorttaxi.dto.HttpPostParam;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class HttpUtil {

    private String url;

    private Integer timeout;


    public HttpUtil(String url, Integer timeout) {
        this.url = url;
        this.timeout = timeout;
    }

    public HttpResult postUrl(HttpPostParam param) throws Exception {
        try {
            HttpEntity httpEntity = buildPostEntity(param);
            HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
            httpRequestFactory.setConnectionRequestTimeout(this.timeout);
            httpRequestFactory.setConnectTimeout(this.timeout);
            httpRequestFactory.setReadTimeout(this.timeout);
            httpRequestFactory.setBufferRequestBody(false);
            RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
            ResponseEntity<Map> response = restTemplate.exchange(this.url, HttpMethod.POST, httpEntity, Map.class);
            if (response.getStatusCode() != HttpStatus.OK) {
                throw new Exception("请求失败:" + response.getStatusCodeValue());
            }
            HttpResult httpResult = JSONObject.parseObject(JSON.toJSONString(response.getBody()), HttpResult.class);
            return httpResult;
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

    private <T> HttpEntity buildPostEntity(T param) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        headers.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
        Map dataMap = new HashMap();
        Class<?> paramClass = param.getClass();
        for (Field field : paramClass.getDeclaredFields()) {
            if (!"host".equals(field.getName())) {
                Object value = getProperty(param, field.getName());
                if (value != null) {
                    dataMap.put(field.getName(), value);
                }
            }
        }
        return new HttpEntity(dataMap, headers);
    }

    public static <T> Object getProperty(Object bean, String propertyName) throws Exception {
        PropertyDescriptor pd = new PropertyDescriptor(propertyName, bean.getClass());
        return pd.getReadMethod().invoke(bean);
    }
}
